import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:proj_sfv/component/SimpleVideo.dart';
import 'package:proj_sfv/component/VideoEditDialog.dart';
import 'package:proj_sfv/component/VideoSearch.dart';
import 'package:proj_sfv/pages/VideoEditPage.dart';
import 'package:proj_sfv/pages/addFriendPage.dart';
import 'package:proj_sfv/pages/cameraPage.dart';
import 'package:proj_sfv/pages/UserVoListPage.dart';
import 'package:proj_sfv/pages/friendPage2.dart';
import 'package:proj_sfv/pages/friendRequestsPage.dart';
import 'package:proj_sfv/pages/loginPage.dart';
import 'package:proj_sfv/pages/messagePage.dart';
import 'package:proj_sfv/pages/myPage.dart';
import 'package:proj_sfv/pages/myVideoDetailPage.dart';
import 'package:proj_sfv/pages/registerPage.dart';
import 'package:proj_sfv/pages/userDetailPage.dart';
import 'package:proj_sfv/pages/userInfoPage.dart';
import 'package:proj_sfv/pages/userProfilePage.dart';
import 'package:proj_sfv/pages/videoCollectorPage.dart';
import 'package:proj_sfv/pages/videoPage.dart';
import 'package:proj_sfv/pages/videoSearchDetailPage.dart';
import 'package:proj_sfv/store/MyAppState.dart';
import 'package:proj_sfv/store/MyArguments.dart';
import 'package:redux/redux.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';


var store = Store<MyAppState>(_reducer, initialState: MyAppState.initState());

final CoreServicesImpl _coreInstance = TIMUIKitCore.getInstance();

MyAppState _reducer(MyAppState myAppState, dynamic action) {
  if (action.runtimeType == LoginAction) {
    return MyAppState(action.id, action.token, myAppState.navigateBarHidden, 0);
  } else if (action.runtimeType == SystemActions) {
    switch(action) {
      case SystemActions.HideNavigateBar: {
        return MyAppState.setNavigateHidden(myAppState);
      }
      case SystemActions.NextVideo: {
        return MyAppState.setCurrentVideo(myAppState, 1);
      }
      case SystemActions.PreVideo: {
        return MyAppState.setCurrentVideo(myAppState, -1);
      }
      default:
        return myAppState;
    }
  } else
    return myAppState;
}

void main() {
  runApp(MyApp());
}


class MyApp extends StatefulWidget {

  MyApp();

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    return StoreProvider(
      store: store,
      child:  MaterialApp(
        routes: {
          // 路由
          "/home": (context) => HomeNavigate(),
          "/video": (context) => VideoPage(),
          "/message": (context) => MessagePage(),
          "/friend": (context) => Text("friend page"),
          "/my": (context) => MyPage(),
          "/user/login": (context) => LoginPage(),
          "/user/register": (context) => RegisterPage(),
          "/user/info": (context) => UserInfoPage(),
          "/user/video": (context) => SimpleVideo(VideoPageType.MY),
          "/user/video/like": (context) => SimpleVideo(VideoPageType.LIKE),
          "/user/video/dislike": (context) => SimpleVideo(VideoPageType.DISLIKE),
          "/user/video/collect": (context) => VideoCollectorPage(),
          "/user/video/collector/detail": (context) => SimpleVideo(VideoPageType.COLLECT),
          "/user/friend/add": (context) => AddFriendPage(),
          "/user/profile": (context) => UserProfilePage(),
          "/video/search/detail": (context) => VideoSearchDetailPage(),
          "/user/friend/requests": (context) => FriendRequestsPage(),
        },
        initialRoute: "/home",
        title: "ProjSFV",
        // initialRoute: "/video",
        // home: HomeNavigate(),
      ),
    );
  }
}

class HomeNavigate extends StatefulWidget {
  const HomeNavigate();

  @override
  State<HomeNavigate> createState() => _HomeNavigateState();
}

class _HomeNavigateState extends State<HomeNavigate> {

  int _currentIndex = 0;

  static List<Widget> _widgets = <Widget> [
    VideoPage(),
    MessagePage(),
    CameraPage(),
    FriendPage2(),
    MyPage()
  ];

  void _onItemTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }
  void handleTIMCallback(TIMCallback callbackValue){
    // tencent im回调
    switch (callbackValue.type) {
      case TIMCallbackType.API_ERROR: {
        // SDK错误
        print(
            "Error from TUIKit: ${callbackValue.errorMsg}, Code: ${callbackValue.errorCode}");
        if (callbackValue.errorCode == 10004 &&
            callbackValue.errorMsg?.contains("not support @all")) {

        } else {
          Fluttertoast.showToast(
              msg: callbackValue.errorMsg ?? callbackValue.errorCode.toString(),
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.CENTER,
              timeInSecForIosWeb: 1,
              backgroundColor: Colors.red,
              textColor: Colors.white,
              fontSize: 16.0
          );
        }
        break;
      }
      case TIMCallbackType.FLUTTER_ERROR:{
        // Flutter原始异常
        break;
      }
      case TIMCallbackType.INFO: {
        // 场景信息

        print('current text: ${callbackValue.infoRecommendText}');
        break;
      }
    }
  }
  @override
  void initState() {
    _coreInstance.init(
      sdkAppID: 1400795083,
      loglevel: LogLevelEnum.V2TIM_LOG_ERROR,
      onTUIKitCallbackListener:  handleTIMCallback,
      listener: V2TimSDKListener(
        // im各种事件的监听
        onConnectFailed: (code, error) => {
          print('连接im服务失败: $code error: $error')
        },
        onConnectSuccess: () => {
          print('连接im服务器成功')
        },
        onConnecting: () => {
          print('正在连接')
        },
        onUserSigExpired: () => {
          print('im登陆凭证过期')
          // TODO 根据登陆情况决定是否更新
        },
        onUserStatusChanged: (List<V2TimUserStatus> userStatusList) {
          for (var item in userStatusList) {
            print('im用户状态变更: 用户状态: ${item.customStatus} 用户自定义状态: ${item.statusType}');
          }
        },
        onSelfInfoUpdated: (V2TimUserFullInfo fullInfo) {
          print('im用户状态更新: 允许加好友类型 ${fullInfo.allowType}');
        },
      ),
    );
    SharedPreferences.getInstance().then((value) {
      String sig = value.getString("sig");
      int id = value.getInt("id");
      TIMUIKitCore.getInstance().login(userID: id.toString(), userSig: sig).then((value) =>
      {
        print('im login result code: ${value.code} desc: ${value.desc}')
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> _appBars = <Widget> [
      VideoSearch(),
      Text("聊天"),
      Text("上传视频"),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        mainAxisSize: MainAxisSize.max,
        children: [
          Text("好友"),
          ElevatedButton.icon(
            icon: const Icon(Icons.add, size: 18),
            label: Text("添加好友"),
            onPressed: () {
              Navigator.pushNamed(context, "/user/friend/add");
            },
          ),
        ],
      ),
      Text("我的")
    ];
    var theme = Theme.of(context).iconTheme;
    var copyWith = theme.copyWith(color: Colors.grey);
    return Scaffold(
      appBar: AppBar(
        title: _appBars.elementAt(_currentIndex),
        automaticallyImplyLeading: false,
      ),
      body: _widgets.elementAt(_currentIndex),
      bottomNavigationBar: StoreConnector<MyAppState, bool> (
        converter: (store) {
          return store.state.navigateBarHidden;
        },
        builder: (context, flag) {
          return Visibility(
            visible: !flag,
            child: BottomNavigationBar(
              unselectedIconTheme: copyWith,
              backgroundColor: Colors.black87,
              items: <BottomNavigationBarItem>[
                BottomNavigationBarItem(
                    icon: Icon(Icons.video_call_outlined), label: "视频"),
                BottomNavigationBarItem(
                    icon: Icon(Icons.message_outlined), label: "消息"),
                BottomNavigationBarItem(
                    icon: Icon(Icons.add_a_photo), label: "上传视频"),
                BottomNavigationBarItem(
                    icon: Icon(Icons.people_outline), label: "好友"),
                BottomNavigationBarItem(
                    icon: Icon(Icons.account_box_outlined), label: "我的"),
              ],
              currentIndex: _currentIndex,
              selectedItemColor: Colors.amber[800],
              onTap: _onItemTapped,
            ),
          );
        },
      ),
    );
  }
}


